package com.swan.web.aop;

import com.swan.web.auto.config.WebConfig;
import com.swan.core.utils.id.IdUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

/** Logback logId 自动注入
 * @author zongf
 * @date 2025-02-05
 **/
public class LogbackLogIdInjectInterceptor implements ServletInterceptor {

    private String logIdName = "LOG_ID";

    private String responseHeaderLogId = "X-Log-Id";

    public LogbackLogIdInjectInterceptor(WebConfig webConfig) {
        if (StringUtils.hasText(webConfig.getLogback().getLogIdName())) {
            this.logIdName = webConfig.getLogback().getLogIdName();
        }
        if (StringUtils.hasText(webConfig.getResponse().getHeaderLogId())) {
            this.responseHeaderLogId = webConfig.getResponse().getHeaderLogId();
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put(logIdName, IdUtil.generateLogId());

        // 在请求时，直接写入响应头，防止后续拦截器或者过滤器串改 response
        response.setHeader(this.responseHeaderLogId, MDC.get(logIdName));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove(logIdName);
    }

    @Override
    public String[] pathPatterns() {
        return new String[]{ "/**" };
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
